const Router = require('koa-router');
const router = new Router();
const dotenv = require('dotenv');
const axios = require('axios');
dotenv.config();  // 让 node 运行时去读取.env 中的内容

const apiKey = process.env.DASHSCOPE_API_KEY;

router.post('/tongyi/video', async (ctx) => {
    const message = ctx.request.body.content; // 前端传过来的消息
    const data = {
        model: "wanx2.1-t2v-turbo", // 模型名称
        // messages: [
        //     {
        //         role: 'user', // 角色
        //         content: message
        //     }
        // ],
        input: {
            prompt: message
        },
        parameters: {
            "size": "1280*720"
        }
    }

    const headers = {
        'X-DashScope-Async': 'enable',
        'Authorization': `Bearer sk-2306c28e001a4397af9bffb951fe179d`,
        'Content-Type': 'application/json'
    };

    try {
        const response = await axios.post("https://dashscope.aliyuncs.com/api/v1/services/aigc/video-generation/video-synthesis", data, { headers });
        const task_id = response.data.output.task_id;

        //console.log(response.data.message.content);
        //console.log('图像生成成功:', response.data.output.task_id);

        // 轮询任务状态
        const result = await pollTaskStatus(task_id, headers);

        if (result.output.task_status === 'SUCCEEDED') {
            //结果
            console.log(result.output)
            ctx.body = {
                code: 200,
                content: result.output // 返回生成的图像链接
            };
        } else {
            ctx.body = {
                code: 500,
                message: '任务失败，请稍后再试'
            };
        }
    } catch (error) {
        console.error('请求失败:', error);
        ctx.body = {
            code: 500,
            message: '请求失败，请稍后重试'
        };
    }
});

// 获取任务状态的函数
async function getTaskStatus(task_id, headers) {
    try {
        const response = await axios.get(`https://dashscope.aliyuncs.com/api/v1/tasks/${task_id}`, { headers });
        return response.data;
    } catch (error) {
        console.error("Error fetching task status:", error.message);
        throw error;
    }
}

// 轮询任务状态
async function pollTaskStatus(task_id, headers) {
    while (true) {
        try {
            const statusResponse = await getTaskStatus(task_id, headers);
            const task_status = statusResponse.output.task_status;

            console.log(`Current task status: ${task_status}`);

            if (task_status === 'SUCCEEDED') {
                console.log("Task completed successfully!");

                //console.log(statusResponse.output.results)
                //console.log(statusResponse);
                return statusResponse;
            } else if (task_status === 'FAILED') {
                console.log("Task failed.");
                throw new Error("Task failed.");
            }

            await new Promise(resolve => setTimeout(resolve, 5000)); // 每隔5秒检查一次状态
        } catch (error) {
            console.error("Error during polling:", error.message);
            throw error;
        }
    }
}

module.exports = {
    videoRouter: router
};